package com.stylefeng.guns.modular.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.model.DTO.RoomDTO;
import com.stylefeng.guns.modular.system.model.DTO.RoomPropertyDTO;
import com.stylefeng.guns.modular.system.model.DTO.RoomPropertyDTOWithNumber;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 控制器
 *
 * @author kai_zhang
 * @Date 2018-05-28 09:25:31
 */
@Transactional
@Controller
@RequestMapping("/rawRoom")
public class RawRoomController extends BaseController {

    private String PREFIX = "/system/rawRoom/";

    @Autowired
    private IRawRoomService rawRoomService;
    @Resource
    private IUserService userService;
    @Resource
    private IRawRoomExpenseService rawRoomExpenseService;
    @Resource
    private IRoomService roomService;
    @Resource
    private IRoomExpenseService roomExpenseService;
    @Resource
    private IRoomPropertyMiddleService roomPropertyMiddleService;
    @Resource
    private IRoomPropertyService roomPropertyService;

    /**
     * 删除(新修改删除方法)，删除房间对象同时删除房间费用和房间资产；
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer roomId) {
        rawRoomService.deleteRoomById(roomId);
        return SUCCESS_TIP;
    }

    /**
     * 修改房间详情
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Room room, String expens, String propertyList) {
        if (propertyList == null || "".equals(propertyList) || "[]".equals(propertyList)) {
            return null;
        }
        //如果费用不为空，设置房间的到期时间
        if (!"[]".equals(expens)) {
            setEndDate(room, expens);
        }

        int roomId = room.getId();
        //首先修改room对象
        roomService.updateById(room);

        //删除资产，插入新的资产；
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.setEntity(new RoomPropertyMiddle());
        entityWrapper.where("room_id = {0}", roomId);
        roomPropertyMiddleService.delete(entityWrapper);


        //创建资产中间表对象集合
        //插入资产信息
        List<RoomPropertyDTOWithNumber> properties = JSONArray.parseArray(propertyList, RoomPropertyDTOWithNumber.class);
        //创建中间表对象集合Div.style.display = "flex";
        List<RoomPropertyMiddle> list = new ArrayList<>();
        RoomPropertyMiddle middle = null;
        for (RoomPropertyDTOWithNumber roomProperty : properties) {
            Integer propertyId = roomProperty.getId();
            Integer number = roomProperty.getNumber();

            middle = new RoomPropertyMiddle();
            middle.setPropertyId(propertyId);
            middle.setRoomId(roomId);
            middle.setNumber(number);

            list.add(middle);
        }
        roomPropertyMiddleService.insertBatch(list);

        //删除费用，插入新的费用
        entityWrapper.setEntity(new RoomExpense());
        roomExpenseService.delete(entityWrapper);
        if (!"[]".equals(expens)) {
            //费用清单不为空才执行插入操作
            List<RoomExpense> expenses = JSONArray.parseArray(expens, RoomExpense.class);
            roomExpenseService.insertBatch(expenses);
        }

        return SUCCESS_TIP;
    }


    /**
     * 跳转到修改房间对象页面
     */
    @RequestMapping(value = "/room_edit/{roomId}")
    public String roomEdit(@PathVariable Integer roomId, Model model) {
        if (ToolUtil.isEmpty(roomId)) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        //查询数据
        //返回房间对象
        Room room = this.roomService.selectById(roomId);
        model.addAttribute("item", room);
        //返回费用集合
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.setEntity(new RoomExpense());
        entityWrapper.where("room_id = {0}", roomId);
        List roomExpenseList = roomExpenseService.selectList(entityWrapper);

        model.addAttribute("roomExpenseList", roomExpenseList);
        //返回资产对象
        List<RoomPropertyDTOWithNumber> roomPropertyDTOS = roomPropertyService.selectByRoomId(roomId);
        model.addAttribute("propertyList", roomPropertyDTOS);

        return PREFIX + "/rawRoom_edit.html";
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Room room, String expens, String propertyList, HttpServletRequest request) {
        if (propertyList == null || "".equals(propertyList) || "[]".equals(propertyList)) {
            return null;
        }
        //参数的非空判断
        String name1 = room.getName();

        //设置房间到期时间
        if (!"[]".equals(expens)) {
            setEndDate(room, expens);
        }

        //在房屋对象中插入用户ID
        ShiroUser shiroUser = (ShiroUser) request.getSession().getAttribute("shiroUser");
        Integer userId = shiroUser.getId();
        room.setUserId(userId);
        //插入房间信息
        roomService.insert(room);
        int roomId = room.getId();

        if (!"[]".equals(expens)) {
            List<RoomExpense> expenses = JSONArray.parseArray(expens, RoomExpense.class);
            //费用不为空才执行此操作
            //插入费用信息
            for (RoomExpense roomExpense : expenses) {
                //设置费用对应的房间ID
                roomExpense.setRoomId(roomId);
            }
            roomExpenseService.insertBatch(expenses);
        }

        //插入资产信息
        List<RoomPropertyDTOWithNumber> properties = JSONArray.parseArray(propertyList, RoomPropertyDTOWithNumber.class);
        //创建中间表对象集合Div.style.display = "flex";
        List<RoomPropertyMiddle> list = new ArrayList<>();
        RoomPropertyMiddle middle = null;
        for (RoomPropertyDTOWithNumber roomProperty : properties) {
            Integer propertyId = roomProperty.getId();
            Integer number = roomProperty.getNumber();

            middle = new RoomPropertyMiddle();
            middle.setPropertyId(propertyId);
            middle.setRoomId(roomId);
            middle.setNumber(number);

            list.add(middle);
        }
        roomPropertyMiddleService.insertBatch(list);

        return SUCCESS_TIP;
    }

    /**
     * 用于毛坯房房源管理页面的房间对象查询
     *
     * @return
     */
    @RequestMapping("/selectRoomForManage")
    @ResponseBody
    public Object selectRoomForManage(String condition, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        if (condition != null) {
            //前台传递了模糊查询条件；
            params.put("condition", condition);
        }
        //获取用户信息
        ShiroUser shiroUser = (ShiroUser) request.getSession().getAttribute("shiroUser");
        Integer userId = shiroUser.getId();
        User user = this.userService.selectById(userId);
        String roleid = user.getRoleid();

        //判断，如果未超级管理员，查询所有房源，否则只查询对应操作员的房源；
        List<RoomDTO> roomDTOS = null;
        if ("1".equals(roleid)) {
            //查询所有
            roomDTOS = rawRoomService.selectRawRoomForManage(params);
        } else {
            //查询特定管理员的房源信息
            params.put("userId", userId);
            roomDTOS = rawRoomService.selectRawRoomForManage(params);
        }
        return roomDTOS;
    }

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "rawRoom.html";
    }

    /**
     * 跳转到添加
     */
    @RequestMapping("/rawRoom_add")
    public String rawRoomAdd() {
        return PREFIX + "rawRoom_add.html";
    }

    /**
     * 跳转到修改
     */
    @RequestMapping("/rawRoom_update/{rawRoomId}")
    public String rawRoomUpdate(@PathVariable Integer rawRoomId, Model model) {
//        RawRoom rawRoom = rawRoomService.selectById(rawRoomId);
//        model.addAttribute("item", rawRoom);
//        LogObjectHolder.me().set(rawRoom);
        return PREFIX + "rawRoom_edit.html";
    }


    /**
     * 根据月租以及起租日期设置房间的到期时间
     */
    public void setEndDate(Room room, String expens) {
        List<RoomExpense> expenses = JSONArray.parseArray(expens, RoomExpense.class);
        //首先遍历费用信息，根据费用中的月租选项，得到房屋的起租日期和结束日期；
        for (RoomExpense roomExpense : expenses) {
            String name = roomExpense.getName();
            if ("月租".equals(name)) {
                Integer valuationType = roomExpense.getValuationType();
                //得到起租日期
                Date startDate = room.getStartDate();
                if (startDate == null) {
                    //如果起租日期为空，直接结束方法，返回
                    return;
                }
                //判断计量单位，得到租赁结束日期；
                Date endDate = null;
                switch (valuationType) {
                    case 5://押一付一
                        endDate = DateUtils.getDateAfterMonth(startDate, 1);
                        break;
                    case 6://押一付2
                        endDate = DateUtils.getDateAfterMonth(startDate, 2);
                        break;
                    case 7://押一付3
                        endDate = DateUtils.getDateAfterMonth(startDate, 3);
                        break;
                    case 8://押一付4
                        endDate = DateUtils.getDateAfterMonth(startDate, 4);
                        break;
                    case 9://押一付5
                        endDate = DateUtils.getDateAfterMonth(startDate, 5);
                        break;
                    case 10://押一付5
                        endDate = DateUtils.getDateAfterMonth(startDate, 6);
                        break;
                    case 11://押一付5
                        endDate = DateUtils.getDateAfterMonth(startDate, 7);
                        break;
                    case 12://押一付5
                        endDate = DateUtils.getDateAfterMonth(startDate, 8);
                        break;
                    case 13://押一付5
                        endDate = DateUtils.getDateAfterMonth(startDate, 9);
                        break;
                    case 14://押一付5
                        endDate = DateUtils.getDateAfterMonth(startDate, 10);
                        break;
                    case 15://押一付5
                        endDate = DateUtils.getDateAfterMonth(startDate, 11);
                        break;
                    case 16://押一付5
                        endDate = DateUtils.getDateAfterMonth(startDate, 12);
                        break;
                }
                //room对象设置起租日期和到期时间
                room.setEndDate(endDate);
            }
        }
    }
}
